package com.android.sq.zouqi.event;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.LinkedList;

import org.apache.commons.lang.StringEscapeUtils;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.android.sq.zouqi.Constants;
import com.android.sq.zouqi.R;
import com.android.sq.zouqi.bdmap.pScrChooseLocation;
import com.android.sq.zouqi.main.pScrMain;
import com.android.sq.zouqi.user.pTableUserInfo;
import com.baidu.mapapi.MapActivity;



/* 如果新活动创建成功，当返回pScrMain时，设置pScrMain.event_interface_reflash = true;
 * 如果没有成功，或者直接点击返回键到pScrMain，reflash不刷新
 * 
 * 首先是根据id调用getCurrentEvent返回的pCurrentEvent判断是新建活动还是修改活动，
 * 如果是新建活动，构造一个空的pCurrentEvent，如果是修改活动，pCurrentEvent是一个有值对象
 */
public class pScrEventInfo extends MapActivity implements OnClickListener {
	private String TAG = "pNewEvent";
	private Context context;
	private int user_id;
	
	private pCtrlEventInfo ctrl_event;
	
	private boolean is_gps_enable = false;
	//private pTableLocationInfo pLocation = null;
	private pTableEventInfo pCurrentEvent;
	private int pCurrentEventId;
	private boolean IS_NEW_EVENT = true;
	
	private int pCurrentLocationId;
	
	// 活动别名
	private EditText byname_et;
	private String byname;
	// 开始时间和持续时间
	private String cur_time = null;
	private TextView start_tv, duration_tv;
	
	private Button start_select_btn, duration_select_btn;
	
	// 用于DatePicker和TimerPicker的初始化显示
	// 当是新建活动，都显示为当前时间
	private int dsp_year, dsp_month, dsp_day, dsp_hour, dsp_minute;
	
	private final static int START_DATE_DIALOG_ID = 0;
	private final static int START_TIME_DIALOG_ID = 1;
	private final static int DURATION_DATE_DIALOG_ID = 2;
	private final static int DURATION_TIME_DIALOG_ID = 3;
	
	// 判断当前是选择开始时间还是持续时间
	private boolean start_select = true;	// true表示是选择开始时间， false表示选择持续时间
	
	// 活动location
	/*private MapView location_mv;			// google map
	private MapController map_controller;
	private GeoPoint geo_point;
	private List<Overlay> overlay_list;
	private Paint paint;
	private GeoPoint cur_geo_point = null;*/
	private TextView location_tv;
	private EditText location_et;
	private Button chs_loc_btn;
	
	// 活动参与人
	private ListView pListParticipants;
	private LinkedList<pTableUserEvent> participants_list;
	private LinkedList<pTableUserInfo> participants_info_list;
	private ParticipantsLVAdapter participants_adapter;
	
	//保存
	private Button submit_btn, back_btn;
	
	private SwitchFuncThread switch_func_thread;
	private static final int GET_CUREVENT_INFO_SIGNAL = 0;
	private static final int GET_LOCATION_INFO_SIGNAL = 1;
	private static final int GET_PARTICIPANTS_INFO_SIGNAL = 2;
	public static final int GET_GPS_START_SIGNAL = 3;
	private static final int SAVE_LOCATION_INFO_SIGNAL = 4;
	private static final int SAVE_EVENT_INFO_SIGNAL = 5;
	private static final int SAVE_PARTICIPANTS_INFO_SIGNAL = 6;
	private static final int SAVE_SUCCESS_SIGNAL = 7;
	
	public static final int ScrChooseLocation = 1;			// 选择地址
	public static final int ScrChooseParticipants = 2;		// 选择参与好友
	// 消息处理器
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			int what = msg.what;
			switch(what) {
			case GET_CUREVENT_INFO_SIGNAL:
				Log.e(TAG, "Handler 收到信号get_curevent_info_signal");
				//当获取到当前事件之后，去获取经纬度
				//if (IS_NEW_EVENT) {
					
				//} else {
					//switch_func_thread = new SwitchFuncThread(get_location_info_signal);
					//switch_func_thread.start();
				//}
				// 当获取到活动信息之后，向服务器获取活动邀请的好友信息
				//Log.e(TAG, "Handler 收到信号get_location_info_signal,获取参与好友的信息");
				switch_func_thread = new SwitchFuncThread(GET_PARTICIPANTS_INFO_SIGNAL);
				switch_func_thread.start();
				break;
			case GET_LOCATION_INFO_SIGNAL:
				break;
			case GET_PARTICIPANTS_INFO_SIGNAL:
				// 当获取到活动参与人之后，放入ListView，刷新UI，把相关值填入View中
				pSetParticipants();
				showComponent();
				break;
			case GET_GPS_START_SIGNAL:
				Log.e(TAG, "GPS已经开启，‘选择地址’按钮可以启用");
				chs_loc_btn.setClickable(true);
			case SAVE_LOCATION_INFO_SIGNAL:
				Log.e(TAG, "开线程保存方位信息");
				switch_func_thread = new SwitchFuncThread(SAVE_LOCATION_INFO_SIGNAL);
				switch_func_thread.start();
				break;
			case SAVE_PARTICIPANTS_INFO_SIGNAL:
				Log.e(TAG, "开线程保存邀请好友信息");
				switch_func_thread = new SwitchFuncThread(SAVE_PARTICIPANTS_INFO_SIGNAL);
				switch_func_thread.start();
				break;
			case SAVE_EVENT_INFO_SIGNAL:
				Log.e(TAG, "开线程保存活动信息");
				switch_func_thread = new SwitchFuncThread(SAVE_EVENT_INFO_SIGNAL);
				switch_func_thread.start();
				break;
			case SAVE_SUCCESS_SIGNAL:
				// 保存成功，提示，并跳转到pScrMain界面
				Log.e(TAG, "handler->向pScrMain界面返回");
				savedBackPre();
				break;
			default:
				break;
			}
		}
	};
	
	// 消息信号
	// public final static int 
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.e(TAG, "pScrEventInfo on create");
		setContentView(R.layout.main_pscreventinfo);
		
		this.context = this.getApplicationContext();
		SharedPreferences share = context.getSharedPreferences("USER_INFO", Context.MODE_PRIVATE);
		user_id = share.getInt(Constants.SP_USER_ID, 0);
		//Log.e(TAG, "oncreate, user_id = " + user_id);
		
		ctrl_event = new pCtrlEventInfo(context, handler);
		
		// 从pScrMain中获取参数
		Bundle bundle = this.getIntent().getExtras();
		pCurrentEventId = bundle.getInt("EVENT_ID");	// 如果是修改活动EVENT_ID为一个正值，如果是新建活动EVENT_ID=-1

		//Log.e(TAG, "当前得到的event id = " + pCurrentEventId);
		// 初始化各个组件
		initComponent();
		
		//获取当前时间，用于DATEPICKER的显示
		final Calendar c = Calendar.getInstance();
		// 获取当前时间，用于比较活动开始时间，活动开始时间不能小于当前时间
		cur_time = c.get(Calendar.YEAR) + 
					"-" + pad(c.get(Calendar.MONTH) + 1) + 
					"-" + pad(c.get(Calendar.DAY_OF_MONTH)) + 
					" " + pad(c.get(Calendar.HOUR_OF_DAY)) + 
					":" + pad(c.get(Calendar.MINUTE));
		
		// 通过地理服务获取当前位置，用于新建活动，这里先写死
		/*cur_geo_point = new GeoPoint((int) (29.859259 * 1000000),
									 (int) (119.50000 * 1000000));*/
		// 获取pCurrentEvent对象，用于数据填充
		switch_func_thread = new SwitchFuncThread(GET_CUREVENT_INFO_SIGNAL);
		switch_func_thread.start();
		
		// 设置is_gps_enable，如果is_gps_enable为true，那么点击“选择地点”按钮就会跳转到地图界面，
		// 否则跳转到设置GPS界面
		setOpenGps();
		
		/* if (is_gps_enable) {
			Toast.makeText(this, "请在设置中开启GPS和无线网络定位", Toast.LENGTH_LONG).show();
			// 如果没有开启，选择地点的按钮失效
			chs_loc_btn.setClickable(false);
			Intent myIntent = new Intent(Settings.ACTION_SECURITY_SETTINGS); 
			startActivity(myIntent); 
		} */
	}

	protected void onResume() {
		super.onResume();
		Log.e(TAG, "pScrEventInfo->onResume");
		// 当恢复当前界面，再判断一次is_gps_enable的值
		setOpenGps();
	}
	
	private void setOpenGps() {
		LocationManager alm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE); 
		if( alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) { 
			is_gps_enable = true;
		} else {
			is_gps_enable = false;
		}
	}
	
	protected void onPause() {
		super.onPause();
	}
	
	public void initComponent() {
		//Log.e(TAG, "Start initComponent");
		byname_et = (EditText) findViewById(R.id.byname_et);
		
		start_tv = (TextView) findViewById(R.id.start_tv);
		start_select_btn = (Button) findViewById(R.id.start_select_btn);
		start_select_btn.setOnClickListener(show_date_listener);
		
		duration_tv = (TextView) findViewById(R.id.duration_tv);
		duration_select_btn = (Button) findViewById(R.id.duration_select_btn);
		duration_select_btn.setOnClickListener(show_date_listener);
		
		location_tv = (TextView) findViewById(R.id.location_tv);
		location_et = (EditText) findViewById(R.id.location_et);
		chs_loc_btn = (Button) findViewById(R.id.choose_loc_btn);
		chs_loc_btn.setOnClickListener(chs_loc_listener);
		
		pListParticipants = (ListView) findViewById(R.id.participant_lv);
		
        submit_btn = (Button) findViewById(R.id.new_event_submit_btn);
        back_btn   = (Button) findViewById(R.id.new_event_back_btn);
        
        submit_btn.setOnClickListener(submit_back_listener);
        //back_btn.setOnClickListener(submit_back_listener);
        
        //Log.e(TAG, "Finish initComponent");
	}
	
	public void showComponent() {
		pSetByname();
		pSetStart();
		pSetDuring();
		pSetLocation();
	}
	
	/*
	 * 获取活动信息数据 - pCB04F01
	 * 根据得到的当前活动id，如果id值为-1则返回null，
	 * 否则查询该id相对应活动的详细信息并返回相应的pTableEventInfo类对象，
	 * 由pCurrentEvent接收该对象作为接下去填充数据工作的数据源。
	 */
	private pTableEventInfo getCurrentEvent(int current_event_id) {
		// 如果是新建活动，构造一个空pCurrentEvent对象，用于填充内容，保存之用
		if(-1 == current_event_id) {
			pCurrentEvent = new pTableEventInfo();
			pCurrentEvent.setpEventLatitude(-90);
			pCurrentEvent.setpEventLongitude(-180);
			pCurrentEvent.setpEventOwnerId(user_id);
			IS_NEW_EVENT = true;
		} else {
			pCurrentEvent = ctrl_event.pGetEventInfo(current_event_id);
			IS_NEW_EVENT = false;	// 是修改活动
			// pCurrentLocationId = pCurrentEvent.getpEventLocationId();
		}
		// 当获取到pCurrent通知handler去更新UI，即调用showComponent
		handler.sendEmptyMessage(GET_CUREVENT_INFO_SIGNAL);
		return pCurrentEvent;
	}
	
	/*
	 * 填充活动别名
	 */
	private void pSetByname() {
		if (pCurrentEvent == null) {
			byname_et.setText("请输入活动的别名");
		}
		if (null != pCurrentEvent.getpEventByname()) {
			byname_et.setText(StringEscapeUtils.unescapeJava(pCurrentEvent.getpEventByname()));
		}
	}
	
	/*
	 * 填充活动开始时间 - pCB04F02
	 * 根据pCurrentEvent中的数据在界面上填充活动开始时间。
	 */
	private void pSetStart() {
		// 从数据库中得到的时间是<2012-08-08 12:23:45>,
		// 因此只截取到<2012-07-08 12:12>，去掉秒数，因为时间选择的时候只有到分钟
		// 虽然从pChooseStart中得到的时间是没有秒数的，但是用pCurrentEventId去判断的代价是一样的
		if (pCurrentEvent.getpEventStart() == null) {
			start_tv.setText(cur_time);
		} else {
			String start_time = pCurrentEvent.getpEventStart().substring(0, 16);
			start_tv.setText(start_time);
		}
		
	}
	
	/*
	 * 填充活动持续时间 - pCB04F03
	 * 根据pCurrentEvent中的数据在界面上填充活动持续时间。
	 */
	private void pSetDuring() {
		if (pCurrentEvent.getpEventDuration() == null) {
			duration_tv.setText(cur_time);
		} else {
			String duration_time = pCurrentEvent.getpEventDuration().substring(0, 16);
			duration_tv.setText(duration_time);
		}
	}
	
	/*
	 * 从服务器获取pTableLocationInfo
	 */
	/*private pTableLocationInfo pGetLocation(int location_id) {
		//Log.e(TAG, "Start pGetLocation");
		if (!IS_NEW_EVENT) {
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			params.add(new BasicNameValuePair(Constants.PARAM_USER_ID, "" + location_id));
			ServerData server_data = new ServerData(Constants.IP_STR + get_location_info_url, params);
			String json_str = server_data.getResultJsonString();
			
			Type listType = new TypeToken<LinkedList<pTableLocationInfo>>() {}.getType();
			Gson gson = new Gson();
			LinkedList<pTableLocationInfo> locations = gson.fromJson(json_str, listType);
			Iterator<pTableLocationInfo> iterator = (Iterator<pTableLocationInfo>)(locations.iterator());
			if (iterator != null) {
				pLocation = (pTableLocationInfo)(iterator.next());
			}
		} else {
			// 设置成-1.0，表示是新建活动 
			// 纬度是赤道0度，北纬为正，南纬为负，-90～90度 
			// 经度是子午线为0度，东经为正，西经为负，-180～180 
			// 因为不能设置为null，所以只能设置为非正常值 
			pLocation = new pTableLocationInfo();
			pLocation.setpLatitude(-91.0);  
			pLocation.setpLongitude(-181.0);
			pLocation.setpByname("");
			pLocation.setpAddress("");
		}
		handler.sendEmptyMessage(get_location_info_signal);
		return pLocation;
	}*/
	
	/*
	 * 填充活动地点 - pCB04F04
	 * 根据pCurrentEvent中的数据在界面上填充活动地点。
	 */
	private void pSetLocation() {
		String address = null;
		if (!IS_NEW_EVENT) {
			location_tv.setText("m经纬度:(" + pCurrentEvent.getpEventLatitude() + ", " 
						+ pCurrentEvent.getpEventLongitude() + ")");
			address = StringEscapeUtils.unescapeJava(pCurrentEvent.getpEventAddress());
			location_et.setText(address);
			
		} else {
			location_tv.setText("n经纬度:(" + pCurrentEvent.getpEventLatitude() + ", " 
						+ pCurrentEvent.getpEventLongitude() + ")");
			address = StringEscapeUtils.unescapeJava(pCurrentEvent.getpEventAddress());
			location_et.setText(address);
		}
		Log.e(TAG, "address = " + address);
	}
	
	/*
	 * 获取邀请的好友数据
	 */
	private void pGetParticipants() {
		// 获得好友邀请列表数据;
		//Log.e("pScrMain", "获取 参与人 列表数据");
		//Log.e("pScrMain", "pGetParticipant- user_id = " + user_id);
		participants_info_list = ctrl_event.pGetUserEvents(pCurrentEventId);
		//Log.e(TAG, "participants_list size = " + participants_list.size());
		handler.sendEmptyMessage(GET_PARTICIPANTS_INFO_SIGNAL);
	}
	/*
	 * 填充邀请的好友 - pCB04F06
	 * 在界面上填充已经邀请的好友，根据当前活动id得到活动参与人的数组并填充相应列表。
	 */
	private void pSetParticipants() {
		participants_adapter = new ParticipantsLVAdapter(pScrEventInfo.this,
				participants_info_list, R.layout.screventinfo_participants_item);
		pListParticipants.setAdapter(participants_adapter);
		//setListViewHeightBasedOnChildren(pListParticipants);
	}
	
	/*
	 * 选择活动开始时间 - pCB04F09
	 * 点击活动开始时间的部分跳出一个DataPickerDialogr设置开始时间
	 * <2012-07-08 12:12:12>
	 */
	private void pChooseStart() {
		//Log.e(TAG, "开始的时间");
		start_select = true;
		// 如果当前pCurrentEvent的开始时间为空，设置Picker为当前时间
		if (pCurrentEvent.getpEventStart() == null) {
			dsp_year 	= Integer.parseInt(cur_time.substring(0, 4));
			dsp_month 	= Integer.parseInt(cur_time.substring(5, 7)) - 1;
			dsp_day		= Integer.parseInt(cur_time.substring(8, 10));
			dsp_hour 	= Integer.parseInt(cur_time.substring(11, 13));
			dsp_minute 	= Integer.parseInt(cur_time.substring(14, 16));
		} else {
			dsp_year 	= Integer.parseInt(pCurrentEvent.getpEventStart().substring(0, 4));
			dsp_month 	= Integer.parseInt(pCurrentEvent.getpEventStart().substring(5, 7)) - 1;
			dsp_day		= Integer.parseInt(pCurrentEvent.getpEventStart().substring(8, 10));
			dsp_hour 	= Integer.parseInt(pCurrentEvent.getpEventStart().substring(11, 13));
			dsp_minute 	= Integer.parseInt(pCurrentEvent.getpEventStart().substring(14, 16));
		}
		showDialog(START_DATE_DIALOG_ID);
	}
	
	/*
	 * 选择活动持续时间 - pCB04F10
	 * 点击活动持续时间的部分跳出一个下拉菜单对话框设置持续时间
	 */
	public void pChooseDuration() {
		//Log.e(TAG, "持续的时间");
		start_select = false;
		if (pCurrentEvent.getpEventDuration() == null) {
			dsp_year 	= Integer.parseInt(cur_time.substring(0, 4));
			dsp_month 	= Integer.parseInt(cur_time.substring(5, 7)) - 1;
			dsp_day		= Integer.parseInt(cur_time.substring(8, 10));
			dsp_hour 	= Integer.parseInt(cur_time.substring(11, 13));
			dsp_minute 	= Integer.parseInt(cur_time.substring(14, 16));
		} else {
			dsp_year 	= Integer.parseInt(pCurrentEvent.getpEventDuration().substring(0, 4));
			dsp_month 	= Integer.parseInt(pCurrentEvent.getpEventDuration().substring(5, 7)) - 1;
			dsp_day		= Integer.parseInt(pCurrentEvent.getpEventDuration().substring(8, 10));
			dsp_hour 	= Integer.parseInt(pCurrentEvent.getpEventDuration().substring(11, 13));
			dsp_minute 	= Integer.parseInt(pCurrentEvent.getpEventDuration().substring(14, 16));
		}
		showDialog(DURATION_DATE_DIALOG_ID);
	}
	
	/*
	 * 选择活动地点 - pCB04F05
	 * 点击相应的图案进入选择活动地点界面。（可以的话用返回的新数据刷新活动地点信息）
	 * 在跳转的同时向下一个界面类传值，如果是新建活动时的选择地点则传入两个null值的long，
	 * 如果是修改活动时的选择地点则传入原活动地点信息的两个long型。
	 */
	public void pGotoScrLocation() {
		Log.e(TAG, "进入活动地图界面");
		Intent intent = new Intent(pScrEventInfo.this, pScrChooseLocation.class);
		Bundle bundle = new Bundle();
		double loc_point[] = {pCurrentEvent.getpEventLatitude(), pCurrentEvent.getpEventLongitude()}; 
		bundle.putDoubleArray(Constants.PIN_GEOPOINT, loc_point);
		bundle.putString(Constants.PIN_ADDRESS, StringEscapeUtils.unescapeJava(pCurrentEvent.getpEventAddress()));
		intent.putExtras(bundle);
        startActivityForResult(intent, ScrChooseLocation);
	}
	
	public void savedBackPre() {
		Log.e(TAG,  "活动信息修改成功，返回活动主界面");
		Intent intent = new Intent(pScrEventInfo.this, pScrMain.class);
		Bundle data = new Bundle();
		data.putInt("REFRESH_EVENT", 1);
		intent.putExtras(data);
		setResult(RESULT_OK, intent);   
        finish();
	}
	
	/* 
     * 处理上一个从FzMapActivity的返回结果，包括经纬度和地址，不包括别名，别名是在当前界面自己设置
     */  
    @Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {   
        // TODO Auto-generated method stub   
        super.onActivityResult(requestCode, resultCode, data);   
        Log.e(TAG, "pScrEventInfo - onActivityResult, requestCode = " + requestCode + ", resultCode = " + resultCode);
        switch(requestCode) {   
        case ScrChooseLocation: //执行成功，返回  
        	// 在pScrChooseLocation界面按了返回键
        	if (resultCode == 0) {
        		Log.e(TAG, "直接返回");
        	}
        	// 在pScrChooseLocation界面按了保存
        	else if (resultCode == -1) {
        		Log.e(TAG, "保存返回");
        		if (data != null) {
                    Bundle bundle = data.getExtras();       //获取intent里面的bundle对象   
                    double loc_point[] = bundle.getDoubleArray("loc_point"); 
                    String loc_addr = bundle.getString("loc_addr");
                    Log.e(TAG, "pScrChooseLocation->获取到的地理信息 = " + loc_addr);
                    pCurrentEvent.setpEventLatitude(loc_point[0] / 1000000.0);
                    pCurrentEvent.setpEventLongitude(loc_point[1] / 1000000.0);
                    pCurrentEvent.setpEventAddress(loc_addr);
                    location_tv.setText("活动具体地点(" + pCurrentEvent.getpEventLatitude() + ", " 
                    		+ pCurrentEvent.getpEventLongitude() + ")");
                    location_et.setText(loc_addr);
                }
        	}
            break; 
            /*
             * 用于保存从 邀请好友参与活动界面 返回的数据
             * 需要增加
             */
        case ScrChooseParticipants: 
        	break;
        default:   
        	break;   
        }   
    }  
	
    public boolean pCheckDataValide() {
    	boolean isValide = true;
    	if (byname_et.getText().toString().equals("")) {
    		Toast.makeText(this, "别名为空！", Toast.LENGTH_LONG).show();
    		isValide = false;
    		return isValide;
    	}
    	/*if (pLocation.getpLatitude() < -90 || pLocation.getpLongitude() < -180 || pLocation.getpAddress().equals("")) {
    		Toast.makeText(this, "活动方位信息为空！", Toast.LENGTH_LONG).show();
    		isValide = false;
    		return isValide;
    	}*/
    	if (pCurrentEvent.getpEventStart().equals(pCurrentEvent.getpEventDuration())) {
    		Toast.makeText(this, "请检查开始时间和结束时间对了吗？", Toast.LENGTH_LONG).show();
    		isValide = false;
    		return isValide;
    	}
    	/*if (participants_info_list == null || participants_info_list.size() == 0) {
    		Toast.makeText(this, "还未邀请好友！", Toast.LENGTH_LONG).show();
    		isValide = false;
    		return isValide;
    	}*/
    	return isValide;
    }
    
	/*
	 * 保存活动信息 - pCB04F08
	 * 将界面上的信息收集组成一个pTableEventInfo并向其中填进pCurrentEventId，
	 * 直接送入pCC02.pCC02F02(pTableEventInfo)，
	 * 该函数会判断是否创建新活动还是修改活动信息。
	 * 如果保存成功则返回该活动id，否则返回-1。
	 */
	public int pSaveEventInfo() {
		int return_id = -1;
		pCurrentEvent.set_id(pCurrentEventId);
		pCurrentEvent.setpEventStart(start_tv.getText().toString());
		pCurrentEvent.setpEventDuration(duration_tv.getText().toString());
		pCurrentEvent.setpEventByname(byname_et.getText().toString());
		return_id = ctrl_event.pSaveEventInfo(pCurrentEvent);
		Log.e(TAG, "返回的return_id = " + return_id);
		if(return_id > 0) {
			Message msg = new Message();
			msg.what = SAVE_SUCCESS_SIGNAL;
			msg.obj = "success";
			handler.sendMessage(msg);
			Log.e(TAG, "向handler发送返回前activity的信号");
		}
		return return_id;
	}
	
	/*public int pSaveLocationInfo() {
		int location_id = -1;
		pLocation.setpByname(byname_et.getText().toString());
		Log.e(TAG, "before save location info");
		Log.e(TAG, "       id = " + pLocation.get_id());
		Log.e(TAG, "   byname = " + pLocation.getpByname());
		Log.e(TAG, " latitude = " + pLocation.getpLatitude());
		Log.e(TAG, "longitude = " + pLocation.getpLongitude());
		Log.e(TAG, "  address = " + pLocation.getpAddress());
		pLocation.set_id(pCurrentLocationId);
		// 得到服务器返回的更新标识
		location_id = ctrl_event.pSaveLocationInfo(pLocation);
		if(location_id == -1) {
			Toast.makeText(this, "方位信息更新失败", Toast.LENGTH_LONG).show();
			Log.e(TAG, "方位信息更新失败");
		} else if (location_id == 0) {
			Toast.makeText(this, "方位信息和先前一样，并没有修改", Toast.LENGTH_LONG).show();
			Log.e(TAG, "方位信息和先前一样，并没有修改");
		} else if (location_id > 0) {
			Toast.makeText(this, "方位信息更新成功", Toast.LENGTH_LONG).show();
			Log.e(TAG, "方位信息更新成功");
			handler.sendEmptyMessage(save_participants_info_signal);
		}
		return location_id;
	}*/
	
	/*public int pSaveParticipantsInfo() {
		int result_id = -1;
		result_id = ctrl_event.pSendInvitation(pCurrentEventId, participants_list);
		if(result_id == -1) {
			Toast.makeText(this, "邀请好友信息更新失败", Toast.LENGTH_LONG).show();
			Log.e(TAG, "邀请好友信息更新失败");
		} else if (result_id == 0) {
			Toast.makeText(this, "邀请好友信息和先前一样，并没有修改", Toast.LENGTH_LONG).show();
			Log.e(TAG, "邀请好友信息和先前一样，并没有修改");
		} else if (result_id > 0) {
			Toast.makeText(this, "邀请好友信息更新成功", Toast.LENGTH_LONG).show();
			Log.e(TAG, "邀请好友信息更新成功");
			handler.sendEmptyMessage(save_event_info_signal);
		}
		return result_id;
	}*/
	
	class SwitchFuncThread extends Thread {
		private int signal;
		private String topic;
		public SwitchFuncThread(int signal) {
			this.signal = signal;
		}
		public SwitchFuncThread(int signal, String topic) {
			this.signal = signal;
			this.topic = topic;
		}
		public void run() {
			switch (signal) {
			case  GET_CUREVENT_INFO_SIGNAL :
				pCurrentEvent = getCurrentEvent(pCurrentEventId);
				break;
			case GET_LOCATION_INFO_SIGNAL :
				Log.e(TAG, "run->pGetLocation");
				//pGetLocation(pCurrentEvent.getpEventLocationId());
				break;
			case GET_PARTICIPANTS_INFO_SIGNAL :
				pGetParticipants();
				break;
			case SAVE_LOCATION_INFO_SIGNAL :
				//pSaveLocationInfo();
				break;
			case SAVE_PARTICIPANTS_INFO_SIGNAL :
				//pSaveParticipantsInfo();
				break;
			case SAVE_EVENT_INFO_SIGNAL :
				pSaveEventInfo();
				break;
			default :
				break;
			}
		}
	}
	
	private OnClickListener show_date_listener = new OnClickListener(){
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (v == start_select_btn) {
				start_select = true;
				pChooseStart();
			} else if (v == duration_select_btn) {
				start_select = false;
				pChooseDuration();
			} 
		}
	};
	
	private OnClickListener chs_loc_listener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			if (is_gps_enable) {
				// 转到活动地图界面
				pGotoScrLocation();
			} else {
				// 如果GPS没有开启，跳转到设置中进行设置，通过onResume方法进行判断是否真的已经打勾
				Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
				startActivity(myIntent);
			}
		}
	};
	
	private OnClickListener submit_back_listener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (v == submit_btn) {
				boolean flag = pCheckDataValide();
				// 保存location event 好友列表
				if (flag) {
					Log.e(TAG, "给handler发送保存成功信号");
					handler.sendEmptyMessage(SAVE_EVENT_INFO_SIGNAL);
				}
			} else if(v == back_btn) {
				// 返回ScrMain界面
			}
		}
	};
	
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	@Override
    protected Dialog onCreateDialog(int id) {
		if (id == START_DATE_DIALOG_ID || id == DURATION_DATE_DIALOG_ID) {
			return new DatePickerDialog(this, 	
							mDateSetListener,
							dsp_year, dsp_month, dsp_day);
		} else if (id == START_TIME_DIALOG_ID || id == DURATION_TIME_DIALOG_ID) {
			return new TimePickerDialog(this,
							mTimeSetListener,
							dsp_hour, dsp_minute, true);
		}
        return null;
    }
	
	@Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
            case START_DATE_DIALOG_ID:
                ((DatePickerDialog) dialog).updateDate(dsp_year, dsp_month, dsp_day);
                break;
            case DURATION_DATE_DIALOG_ID:
                ((DatePickerDialog) dialog).updateDate(dsp_year, dsp_month, dsp_day);
                break;
            case START_TIME_DIALOG_ID:
            	((TimePickerDialog) dialog).updateTime(dsp_hour, dsp_minute);
            	break;
            case DURATION_TIME_DIALOG_ID:
            	((TimePickerDialog) dialog).updateTime(dsp_hour, dsp_minute);
        }
    }  
	
	private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {
				@Override
                public void onDateSet(DatePicker view, int year, int month,
                        int day) {
                	if (start_select) {
	                	pCurrentEvent.setpEventStart(year+"-"+pad(month+1)+"-"+pad(day)+" ");
	                	// 选择完日期, 选择时间
	                    showDialog(START_TIME_DIALOG_ID);
                	} else {
                		pCurrentEvent.setpEventDuration(year+"-"+pad(month+1)+"-"+pad(day)+" ");
                		showDialog(DURATION_TIME_DIALOG_ID);
                	}
                	
                }
            };
    
    private TimePickerDialog.OnTimeSetListener mTimeSetListener = 
    		new TimePickerDialog.OnTimeSetListener() {
				@Override
				public void onTimeSet(TimePicker view, int hour, int minute) {
					// TODO Auto-generated method stub
					if (start_select) {
						String pDate = pCurrentEvent.getpEventStart();
						pCurrentEvent.setpEventStart(pDate + pad(hour) + ":" + pad(minute));
						Timestamp stime = new Timestamp(2012,8,21, 0, 0, 0, 0);
						pSetStart();
						pChooseDuration();
					} else {
						String pDate = pCurrentEvent.getpEventDuration();
						pCurrentEvent.setpEventDuration(pDate + pad(hour) + ":" + pad(minute));
						pSetDuring();
					}
					//updateDisplay();
				}
			};        
    
    private static String pad(int c) {
    	if (c >= 10)
    		return String.valueOf(c);
    	else
    		return "0" + String.valueOf(c);
    }
    
    /*
	 * 针对pTableRelation的布适配器
	 * 传递的参数有数据list和布局资源id
	 */
	class ParticipantsLVAdapter extends BaseAdapter {
		// inflater用于将一个XML文件转换成一个视图（View)
		private int layout_id;
		private LayoutInflater inflater;
		private LinkedList<pTableUserInfo> list;
		public ParticipantsLVAdapter(Context context, LinkedList<pTableUserInfo> list, int layout_id) {
			inflater = LayoutInflater.from(context);
			this.list = list;
			this.layout_id = layout_id;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			Object object = list.get(arg0);
			//Log.e(TAG, "getItem , object = " + object);
			return object;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View view = inflater.inflate(layout_id, null);
			TextView pLabelFriendName;
			final pTableUserInfo user_info = (pTableUserInfo) this.getItem(position);
			pLabelFriendName = (TextView) view.findViewById(R.id.participant_name);
			pLabelFriendName.setText("好友：\t\n\t" + user_info.get_id());
			return view;
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}
    
    /*
     * 关于map的方法
     */
    /*class MyLocationOverlay extends Overlay {
		boolean isTouch = false;
		String addStr;
		Point screen_point = new Point();
		Paint paint = null;
		boolean is_draw_pin = false;	// 在Touch事件中标识能否画图钉
		
		Bitmap pin_bmp;
		int bmp_width, bmp_height;
		public MyLocationOverlay(String title, int latitude, int longitude,
				Paint paint) {
			addStr = title;
			geo_point = new GeoPoint(latitude, longitude);
			this.paint = paint;
			pin_bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pin);
			bmp_width = pin_bmp.getWidth();
			bmp_height = pin_bmp.getHeight();
		}
		
		public MyLocationOverlay(String title, GeoPoint point, Paint paint) {
			addStr = title;
			geo_point = point;
			this.paint = paint;
		}
		
		@Override
		public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
				long when) {
			if (shadow) {
				// 将经纬度转换成实际屏幕坐标
				mapView.getProjection().toPixels(geo_point, screen_point);
				// 画出地址名
				canvas.drawText(addStr, screen_point.x, screen_point.y,
						paint);
				//canvas.drawRect(screen_point.x, screen_point.y,
						//screen_point.x + 8, screen_point.y + 8, paint);
				// 画出图钉
				canvas.drawBitmap(pin_bmp, screen_point.x - bmp_width / 2, screen_point.y - bmp_height,
							paint);
			}
			super.draw(canvas, mapView, shadow);
			return true;
		}
		
		@Override
		public boolean onTouchEvent(MotionEvent e, MapView mapView) {
			int action = e.getAction();
			switch (action) {
			case MotionEvent.ACTION_DOWN:
				is_draw_pin = true;
				return false;
			case MotionEvent.ACTION_MOVE:
				is_draw_pin = false;
				return false;
			case MotionEvent.ACTION_UP:
				if (is_draw_pin) {
					byname = byname_et.getText().toString().trim();
					if (byname == null) {
						Toast.makeText(context, "地点别名不能为空", 3000).show();
					} else {
						// 获取创建新活动所需的经纬度值
						addStr = byname;
						float x = e.getX();
						float y = e.getY();
						geo_point = mapView.getProjection().fromPixels(
								(int) x, (int) y);
						longitude = geo_point.getLongitudeE6();
						latitude = geo_point.getLatitudeE6();
						Log.e("BA", "经纬度 = (" + longitude + ", " + latitude + ")");
					}
				}
				return true;
			default:
				return false;
			}
		}
	}
    */
    /*OnTouchListener map_touch_listener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent e) {
			// TODO Auto-generated method stub
			Log.e("BA", "onTouch map.clickable = " + location_mv.isClickable());
			int action = e.getAction();
			switch (action) {
			case MotionEvent.ACTION_DOWN:
				
				return true;
			case MotionEvent.ACTION_MOVE:
				return false;
			case MotionEvent.ACTION_UP:
				byname = byname_et.getText().toString().trim();
				if (byname == null) {
					Toast.makeText(context, "地点别名不能为空", 3000).show();
				} else {
					float x = e.getX();
					float y = e.getY();
					GeoPoint testGeoPoint = location_mv.getProjection().fromPixels(
							(int) x, (int) y);
					Log.e("BA", "testGeoPoint = " + testGeoPoint.getLatitudeE6()
							+ ", " + testGeoPoint.getLongitudeE6());
					MyLocationOverlay myLO = new MyLocationOverlay(byname, testGeoPoint, paint);
					// 因为只要标注一个方位，所以吧前面一个Overlay删掉，保持始终只有一个
					overlay_list.remove(0);
					overlay_list.add(myLO);
				}
				return true;
			default:
				return true;
			}
		}
	};*/
    
    /*public void initMapView() {
	location_mv = (MapView) findViewById(R.id.location_mv);
	location_mv.setSatellite(true);
	// 设置为街景模式
	// location_mv.setStreetView(false);
	// 取得MapController对象(控制MapView)
	map_controller = location_mv.getController();
	location_mv.setEnabled(true);
	location_mv.setClickable(true);
	// 设置地图支持缩放
	location_mv.setBuiltInZoomControls(true);

	// 设置起点为成都
	geo_point = new GeoPoint((int) (30.659259 * 1000000),
			(int) (104.065762 * 1000000));
	// 定位到成都
	map_controller.animateTo(geo_point);
	// 设置倍数(1-21)
	map_controller.setZoom(15);

	paint = new Paint();
	paint.setStrokeWidth(2);
	paint.setARGB(255, 255, 0, 0);
	paint.setStyle(Paint.Style.STROKE);
	
	   //添加Overlay，用于显示标注信息
	   //在Overlay的Touch事件中，如果触发事件，
	   //就修改myLocationOverlay的坐标，会自动调用draw方法进行绘制。
	   //不必进行<Overlay>List进行添加，不过这个可以用于查看活动主界面的成员当前位置
	 
	// 成都 (int) (30.659259 * 1000000), (int) (104.065762 * 1000000)
	// 北京 (int) (39.54 * 1000000), (int) (116.23 * 1000000)
	// 这个值应该从GPS中获得
	MyLocationOverlay myLocationOverlay = new MyLocationOverlay("天府：",
			//(int) (39.54 * 1000000), (int) (116.23 * 1000000),
			(int) (30.659259 * 1000000), (int) (104.065762 * 1000000),
			paint);
	
	  //myLctOverlay = new MyLocationOverlay("天府：", (int) (30.659259 *
	  //1000000), (int) (104.065762 * 1000000), paint);
	 
	overlay_list = location_mv.getOverlays();
	overlay_list.add(myLocationOverlay);
	
	//location_mv.setOnTouchListener(map_touch_listener);
}*/

}
